import mysql.connector
from contextlib import contextmanager

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def get_db_connection():
    connection = mysql.connector.connect(
        host='localhost',
        port=3306,
        user="dwarf_opr",
        password="5wTpObYp8KTqy154",
        database="dwarf_biz"
    )
    return connection

@contextmanager
def get_db():
    connection = get_db_connection()
    cursor = connection.cursor(dictionary=True)  # 使用字典格式返回结果
    try:
        yield cursor     # yeild 关键字返回db游标，供with语句使用
    except mysql.connector.Error as err:
        logger.error(err)
        connection.rollback()
    finally:
        cursor.close()
        connection.close()